<?php 
/*
Plugin Name: Meta Description
Plugin URI: http://shinraholdings.com.com/plugins/meta-description
Description: Adds a meta box for inputting post/page HTML meta descriptions.
Version: 1.0.2
Author: bitacre
Author URI: http://shinraholdings.com/
License: GPLv3 (http://gnu.org/licenses/gpl-3.0.txt)
Copyright 2012 Shinra Web Holdings (http://shinraholdings.com)
*/

// get meta description for post
function swhmd_get_meta_description( $post_id ) {
	return get_post_meta( $post_id, 'meta_description', true ); // returns '' on empty
}

// register the meta box
function swhmd_add_meta_box() {
	add_meta_box( 'add_meta_description_meta_box', 'Meta Description', 'swhmd_draw_meta_box', 'post', 'normal', 'high' );
	add_meta_box( 'add_meta_description_meta_box', 'Meta Description', 'swhmd_draw_meta_box', 'page', 'normal', 'high' );
}

// add meta box text to post meta
function swhmd_save_meta_description( $post_id ) {
	// verify
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
	if ( !wp_verify_nonce( $_POST['swhmd_noncename'], plugin_basename( __FILE__ ) ) ) return;
	if ( $_POST['post_type'] == 'page' ) { if ( !current_user_can( 'edit_page', $post_id ) ) return; }
	else { if ( !current_user_can( 'edit_post', $post_id ) ) return; }

	// update
	update_post_meta( $post_id, 'meta_description', esc_attr( $_POST['swhmd_meta_description_text'] ) );
}

// admin page meta box inner HTML
function swhmd_draw_meta_box( $post ) {
	wp_nonce_field( plugin_basename( __FILE__ ), 'swhmd_noncename' ); 
	?>

<textarea id="swhmd_meta_description_text" name="swhmd_meta_description_text" style="height:4em;width:98%;"><?php echo swhmd_get_meta_description( $post->ID ); ?></textarea>

<?php 
}

// function to insert HTML code
function swhmd_meta_description_filter() { 
	global $post;
	if( is_single() || is_page() ) $meta_description = swhmd_get_meta_description( $post->ID );
	else $meta_description = get_bloginfo( 'description' );
?>
<meta name="description" content="<?php echo $meta_description; ?>" />
<?php 
}


// HOOKS, FILTERS, & ACTIONS
add_action( 'add_meta_boxes', 'swhmd_add_meta_box', 1 );
add_action( 'save_post', 'swhmd_save_meta_description', 10, 1 );
add_action( 'wp_head', 'swhmd_meta_description_filter', 10 );

?>